package uilts;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class C3P0utils {
  private static   ComboPooledDataSource ds=  new ComboPooledDataSource();
//底层里面会自动加载c3p-config.XML文件。
  //获取数据源
  public  static DataSource getDataSource(){
      return  ds;
  }

  //获取连接对象
    public static Connection getConnerction() throws SQLException {

      return  ds.getConnection();
    }


    /*关闭数据库连接*/
    public void closeAll(Connection cn, PreparedStatement pre, ResultSet re){
        if(re!=null){
            try {
                re.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(pre!=null){
            try {
                pre.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(cn!=null){
            try {
                cn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /*增，删，改*/
    public int executeUpdate(String sql ,Object[]obj){
        int i1=0;
        Connection con=null;
        PreparedStatement preparedStatement=null;
        ResultSet re =null;
        try {
            con=  getConnerction();
            /**/
            preparedStatement= con.prepareStatement(sql);
            for(int i=1;i<=obj.length;i++){
                preparedStatement.setObject(i,obj[i-1]);
            }
            /*返回一个int类型的值，就是整个sql语句影响的条数*/
            i1 = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(con,preparedStatement,re);
        }
        return  i1;


    };

}
